package com.tarena.luban.demo.gateway.filters;

import com.alibaba.nacos.common.utils.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
public class AuthenticationTestFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //验证token
        boolean pass=checkToken(exchange);
        if (pass){
            return chain.filter(exchange);
        }else {
            // 模拟代码运行中 无法控制的系统异常
            // throw new RuntimeException("没有验证成功");
            return Mono.error(new RuntimeException("没有验证成功"));
            /*ServerHttpResponse response = exchange.getResponse();
            String authError="您的认证验证失败";
            return response.writeWith(Mono.fromSupplier(
                    () -> response.bufferFactory().wrap(authError.getBytes(StandardCharsets.UTF_8))
            ));*/
        }
    }

    private boolean checkToken(ServerWebExchange exchange) {
        //1 不带token list是空的
        //2 带token 不给值 list不是空 有一个空对象的元素
        //3 带token 给值 ?token=1029343726
        List<String> stringList = exchange.getRequest().getQueryParams().get("token");
        if (CollectionUtils.isNotEmpty(stringList)){
            String token = stringList.get(0);
            if (StringUtils.isNotEmpty(token)){
                return token.matches("^\\d{10}$");
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
